import type { ResumeData, Response } from "../types";

// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 请求配置
const defaultHeaders = {
  "Content-Type": "application/json"
};

// 通用请求函数
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
  const response = await fetch(`${API_BASE_URL}${url}`, {
    headers: {
      ...defaultHeaders,
      ...options.headers
    },
    ...options
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return response.json() as Promise<T>;
}

export const resumeApi = {
  async PostResume(data: ResumeData): Promise<Response> {
    return request("/resume", {
      method: "POST",
      body: JSON.stringify(data)
    });
  }
};

// 错误处理工具
export const handleApiError = (error: unknown): string => {
  if (error instanceof Error) {
    return error.message;
  }
  return "网络请求失败，请检查网络连接";
};
